﻿using System;

using QuickTuner.RadioProtocol.Modules;

namespace QuickTuner.RadioProtocol
{
    public partial class ProtocolAction
    {
        /// <summary>
        /// Checks wether this action is a valid executable action.
        /// Parameters and ParameterString is however, not checked.
        /// </summary>
        public bool CanExecute(IRadio target)
        {
            if (string.IsNullOrEmpty(_module) || string.IsNullOrEmpty(_action))
                return false;

            var module = FindModule(_module);
            if (module == null)
                return false;

            module.Target = target;

            return module.CanExecute(_action, _params);
        }

        /// <summary>
        /// Executes this action with the set parameters on the target radio.
        /// </summary>
        public void Execute(IRadio target)
        {
            // validate parameters
            if (string.IsNullOrEmpty(_module) || string.IsNullOrEmpty(_action))
                throw new InvalidOperationException("No module or action specified.");

            if (target == null)
                throw new ArgumentNullException("target");

            if (!CanExecute(target))
                throw new InvalidOperationException("Unknown recognized module or action.");

            // delegate to the appropriate module
            var module = FindModule(_module);
            module.Target = target;

            module.Execute(_action, _params);
        }

        public ProtocolModuleBase FindModule(string moduleName)
        {
            switch (moduleName.ToUpper()) {
                case "STATIONS":
                    return new StationsModule();
                case "RADIO":
                    return new RadioModule();
            }

            return null;
        }
    }
}